package com.zj.sc8.user.web;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.central.common.entity.Result;
import com.zj.sc8.util.BlockHandlerUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhaojin
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IndexController {

    private final RestTemplate restTemplate;

    @GetMapping("login")
    @SentinelResource(value = "login", blockHandlerClass = BlockHandlerUtils.class, blockHandler = "loginBlockHandler")
    public Result<String> login(String userName) {
        log.info("userName:{}", userName);
        String data = restTemplate.getForEntity("http://PRODUCER/login?userName=" + userName, String.class).getBody();
        return Result.success(data);
    }

    @GetMapping("login2")
    @SentinelResource(value = "login2",blockHandler = "login2BlockHandler")
    public Result<String> login2(String userName) {
        log.info("userName:{}", userName);
        String data = restTemplate.getForEntity("http://PRODUCER/login?userName=" + userName, String.class).getBody();
        return Result.success(data);
    }

    public Result<String> login2BlockHandler(String userName, BlockException exception) {
        log.error("err:[{}]", exception);
        return Result.error(100011, "网络拥堵，请稍后再试。");
    }
}
